package com.zbkj.service.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.RedisKeyConstants;
import com.zbkj.common.enums.UserBillCategoryEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserBill;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.user.AdminUserQueryRequest;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.user.UserDatavalVo;
import com.zbkj.service.dao.user.UserMapper;
import com.zbkj.service.service.user.UserBillService;
import com.zbkj.service.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 客户端用户表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-07-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private FrontTokenComponent frontTokenComponent;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserBillService userBillService;


    @Override
    public PageInfo<User> adminGetList(AdminUserQueryRequest queryRequest) {
        Page<User> pageObj = PageHelper.startPage(queryRequest.getPage(), queryRequest.getLimit());
        List<User> list = userMapper.adminGetList(queryRequest);
        return CommonPage.copyPageInfo(pageObj,list);
    }

    @Override
    public boolean accountRepeatCheck(Long id, String account) {
        int rowNum = userMapper.accountRepeatCheck(id,account);
        return rowNum>0;
    }

    @Override
    public boolean userSaveOrUpdate(User user) {
        boolean flag = false;
        if(Objects.isNull(user)) {
            return flag;
        }
        if(Objects.isNull(user.getId())) {
            //新增用户
            flag = this.save(user);
        } else {
            //更新用户
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.eq(User::getId, user.getId());
            /*if(Objects.nonNull(user.getValidType()) && user.getValidType().intValue() == 1) {
                updateWrapper.set(User::getValidToDate,null);
            }*/
            flag = this.update(user,updateWrapper);
        }
        if(flag) {
            //删除用户缓存
            this.delUserCache(user.getId());
        }
        return flag;
    }

    @Override
    public boolean updateUserInfo(User user) {
        if(Objects.isNull(user) || Objects.isNull(user.getId())) {
            return false;
        }
        boolean flag = this.updateById(user);
        if(flag) {
            //删除用户缓存
            this.delUserCache(user.getId());
        }
        return true;
    }

    @Override
    public User getLoginUserInfo() {
        return this.getUserInfoCache(frontTokenComponent.getUserId());
    }

    @Override
    public User getUserByAccount(String account) {
        if(StringUtils.isBlank(account)) {
            return null;
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account)
                .eq(User::getDeleteFlag,0);
        return this.getOne(queryWrapper,false);
    }

    @Override
    public User getUserById(Long id) {
        if(Objects.isNull(id)) {
            return null;
        }
        return userMapper.selectById(id);
    }

    @Override
    public User getUserInfoCache(Long id) {
        if(Objects.isNull(id)) {
            return null;
        }
        User user = null;
        String cachKey = String.format(RedisKeyConstants.CLIENT_USER_KEY,id);
        String userJson = redisUtil.get(cachKey);
        if(StringUtils.isBlank(userJson)) {
            user = this.getUserById(id);
            if(Objects.nonNull(user)) {
                this.saveUserInCache(user);
            }
        } else {
            user = JSON.parseObject(userJson, User.class);
        }
        return user;
    }

    @Override
    public void saveUserInCache(User user) {
        if(Objects.isNull(user) || Objects.isNull(user.getId())) {
            return;
        }
        String cachKey = String.format(RedisKeyConstants.CLIENT_USER_KEY,user.getId());
        redisUtil.set(cachKey,JSON.toJSONString(user), RedisKeyConstants.CLIENT_USER_EXPIER);
    }

    @Override
    public void delUserCache(Long id) {
        if(Objects.isNull(id)){
            return;
        }
        String cachKey = String.format(RedisKeyConstants.CLIENT_USER_KEY,id);
        redisUtil.delete(cachKey);
    }


    public void userValidCheck(User user) {
        if(Objects.isNull(user) || user.getDeleteFlag() == 1) {
            throw new CommonException("账户已不存在");
        }
        if(user.getStatus() != 0) {
            throw new CommonException("账号已被禁用");
        }
        /*if(user.getValidType() == 0 && Objects.nonNull(user.getValidToDate())
                && user.getValidToDate().getTime() < System.currentTimeMillis()) {
            throw new CommonException("账号已过期");
        }*/
    }

    @Override
    public boolean deductDataval(UserDatavalVo userDatavalVo, List<UserBill> userBillList) {
        boolean res = false;
        if(userDatavalVo.getUserId() <= 0) {
            return res;
        }
        int rowNum = userMapper.deductDataval(userDatavalVo);
        if(rowNum <= 0) {
            return res;
        }
        if(CollectionUtils.isNotEmpty(userBillList)) {
            userBillService.saveBatch(userBillList);
        }
        //this.delUserCache(userDatavalVo.getUserId());
        return true;
    }
    public boolean incrDataval(UserDatavalVo userDatavalVo, List<UserBill> userBillList) {
        boolean res = false;
        if(userDatavalVo.getUserId() <= 0) {
            return res;
        }   
        if(userDatavalVo.getCardDataval()> 0 && Objects.nonNull(userDatavalVo.getYearPid())) {
            // 计算年卡有效期，精确到小时的59分59秒
            Calendar cal = Calendar.getInstance();
            cal.setTime(userDatavalVo.getCurrentDate()); // 使用传递过来的当前日期
            cal.add(Calendar.YEAR, userDatavalVo.getYearCardCount()); // 使用传递过来的年卡数量
            cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            Date cardExpire = cal.getTime();

            // 更新用户年卡信息
            res = this.addUserCardInfo(userDatavalVo.getUserId(), userDatavalVo.getYearPid(), userDatavalVo.getCardDataval(), cardExpire, userDatavalVo.getYearCardCount());
//            Date cardExpire = LocalDateUtil.addYearForEndDate(1);
            //更新用户年卡包
//            res = this.addUserCardInfo(userDatavalVo.getUserId(),userDatavalVo.getYearPid(),userDatavalVo.getCardDataval(), cardExpire);
            if(!res) {
                throw new CommonException("用户年卡记录失败，请稍后重试");
            }
        }
        if(userDatavalVo.getDataval() > 0) {
            int rowNum = userMapper.icrDataval(userDatavalVo.getUserId(), userDatavalVo.getDataval());
            if(rowNum <= 0) {
                return false;
            }
        }
        if(CollectionUtils.isNotEmpty(userBillList)) {
            userBillService.saveBatch(userBillList);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userCardExpireHandle(User user) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getCardId,0)
                .set(User::getCardExpire,null)
                .set(User::getCardDataval, 0)
                .eq(User::getDeleteFlag, 0)
                .eq(User::getCardId, user.getCardId())
                .eq(User::getCardDataval, user.getCardDataval())
                .eq(User::getId, user.getId());
        boolean flag = this.update(wrapper);
        if(!flag) {
            throw new CommonException("用户年卡过期失效更新失败");
        }
        if(user.getCardDataval().longValue() > 0) {
            UserBill userBill = new UserBill();
            userBill.setUserId(user.getId());
            userBill.setPmtype(0);
            userBill.setCategory(UserBillCategoryEnum.BILL_CATEGORY3.getCategory());
            userBill.setCardDataval(user.getCardDataval());
            userBill.setSourceType(0);
            userBill.setSourceId(0L);
            userBill.setYearPid(user.getCardId());
            userBill.setMark(UserBillCategoryEnum.BILL_CATEGORY3.getRemark());
            userBillService.save(userBill);
        }
    }

    @Override
    public boolean icrDataValAndCheckCardId(long userId, Long cardDataval, Long dataval, Long cardId) {
        int rownum = userMapper.icrDataValAndCheckCardId(userId, cardDataval, dataval, cardId);
        return  rownum >0;
    }

//    private boolean addUserCardInfo(long userId, long cardId, long cardDataval, Date cardExpire) {
//        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.set(User::getCardId,cardId)
//                .set(User::getCardExpire,cardExpire)
//                .set(User::getCardDataval, cardDataval)
//                .eq(User::getDeleteFlag, 0)
//                .eq(User::getCardId, 0)
//                .eq(User::getId, userId);
//        wrapper.and(w->w.isNull(User::getCardExpire).or().lt(User::getCardExpire,new Date()));
//        return this.update(wrapper);
//    }


    private boolean addUserCardInfo(long userId, long cardId, long cardDataval, Date cardExpire, int yearCardCount) {
        // 查询用户当前的年卡信息
        User currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new CommonException("用户不存在");
        }

        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId, userId);


        if (currentUser.getCardId() != null && currentUser.getCardExpire() != null && currentUser.getCardExpire().after( new Date())) {
            // 如果用户已有年卡且未过期，在当前年卡失效日期的基础上增加年数
            Calendar cal = Calendar.getInstance();
            cal.setTime(currentUser.getCardExpire());
            cal.add(Calendar.YEAR, yearCardCount); // 增加相应的年数
            cardExpire = cal.getTime();

            wrapper.set(User::getCardExpire, cardExpire); // 更新年卡失效日期
        } else {
            // 如果用户没有年卡或者年卡已过期，直接设置新的年卡信息
            wrapper.set(User::getCardId, cardId)
                    .set(User::getCardExpire, cardExpire)
                    .set(User::getCardDataval, cardDataval);
        }

        return this.update(wrapper);
    }

    @Override
    public List<User> getUsersByIds(List<Long> userIds) {
        if(ObjectUtils.isEmpty(userIds)){
            return new ArrayList<>();
        }
        return this.lambdaQuery().in(User::getId, userIds).list();
    }

    @Override
    public boolean getYearUserFlag(Long id) {
        User one = this.lambdaQuery().eq(User::getId, id).eq(User::getDeleteFlag, 0).one();
        if(ObjectUtils.isEmpty(one)){
            return false;
        }
        if(ObjectUtils.isEmpty(one.getCardExpire())){
            return false;
        }
        if(one.getCardExpire().after(new Date())){
            return true;
        }
        return false;
    }
}
